/**********************************************
** @Author: phy
** @Date:   2017-12-12 14:17:37
** @Last Modified by:   phy
***********************************************/
package models

import (
	"bytes"
	"strconv"
	"strings"

	"github.com/astaxie/beego/orm"
)

type ManageRoleAuth struct {
	RoleId int
	AuthId int `orm:"pk"`

}

func (ra *ManageRoleAuth) TableName() string {
	return TableName("ManageRoleAuth")
}

func ManageRoleAuthAdd(ra *ManageRoleAuth) (int64, error) {
	return orm.NewOrm().Insert(ra)
}

func ManageRoleAuthGetById(id int) ([]*ManageRoleAuth, error) {
	list := make([]*ManageRoleAuth, 0)
	query := orm.NewOrm().QueryTable(TableName("ManageRoleAuth"))
	_, err := query.Filter("RoleId", id).All(&list, "AuthId")
	if err != nil {
		return nil, err
	}
	return list, nil
}

func ManageRoleAuthDelete(id int) (int64, error) {
	query := orm.NewOrm().QueryTable(TableName("ManageRoleAuth"))
	return query.Filter("RoleId", id).Delete()
}

//获取多个
func ManageRoleAuthGetByIds(RoleIds int) (Authids string, err error) {
	list := make([]*ManageRoleAuth, 0)
	query := orm.NewOrm().QueryTable(TableName("ManageRoleAuth"))
	_, err = query.Filter("RoleId", RoleIds).All(&list, "AuthId")
	if err != nil {
		return "", err
	}
	b := bytes.Buffer{}
	for _, v := range list {
		if v.AuthId != 0 && v.AuthId != 1 {
			b.WriteString(strconv.Itoa(v.AuthId))
			b.WriteString(",")
		}
	}
	Authids = strings.TrimRight(b.String(), ",")
	return Authids, nil
}

func ManageRoleAuthMultiAdd(ras []*ManageRoleAuth) (n int, err error) {
	query := orm.NewOrm().QueryTable(TableName("ManageRoleAuth"))
	i, _ := query.PrepareInsert()
	for _, ra := range ras {
		_, err := i.Insert(ra)
		if err == nil {
			n = n + 1
		}
	}
	defer i.Close() // 别忘记关闭 statement
	return n, err
}
func GetUserRightByID(iRight,iUserID int) bool {
	o := orm.NewOrm()
	o.Using("default")
	Gettable := o.QueryTable(TableName("ManageRoleAuth"));
	Gettable = Gettable.Filter("RoleId", iUserID);
	Gettable = Gettable.Filter("AuthId", iRight);
	return Gettable.Exist()	
}